import './index.scss'
import { Card, Form, Input, Button, message } from 'antd'
import React, { useState, useEffect } from 'react';
import logo from '@/assets/logo1.png'
import { useDispatch } from 'react-redux'
import { fetchLogin } from '@/store/modules/user'
import { useNavigate } from 'react-router-dom'


const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  //倒计时验证
  const [data, setData] = useState({ count: 60, show: false })
  //切换状态 
  useEffect(() => {
    let timer = null;
    if (data.show) {
      timer = setInterval(() => {
        if (data.count === 1) {
          clearInterval(timer);
          setData({ count: 60, show: false });
        } else {
          setData(prevData => ({ ...prevData, count: prevData.count - 1 }));
        }
      }, 1000);
    }
    return () => {
      clearInterval(timer);
    };
  });
  const getCheckCode = () => {
    setData({ count: 60, show: true });
  };
  const onFinish = async (value) => {
    console.log(1111);
    console.log(value);
    //触发异步请求
    await dispatch(fetchLogin(value))
    //跳转首页
    navigate('/')
    //提示yonghu
    message.success('登录成功')
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form validateTrigger="onBlur" onFinish={onFinish}>
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号'
              }
            ]}>
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}>
            <Input size="large" placeholder="请输入验证码" className='yanzheng1'/>
          </Form.Item>
          
          <Button onClick={getCheckCode}  disabled={data.show} className="yanzheng">
              {data.show ? `${data.count}秒后重新获取` : '获取验证码'}
            </Button>
          
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block className='yanzheng2'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login